//
//  ViewController.swift
//  VO_Yuejie
//
//  Created by laichunhui on 15/11/16.
//  Copyright © 2015年 lch. All rights reserved.
//
// TODO:
/* 
    class AutomaticCar: Car {
    override var currentSpeed: Double {
    didSet {
    gear = Int(currentSpeed / 10.0) + 1
    }
    }
    } 
*/

import UIKit
import SnapKit
import SVProgressHUD

/// 底部工具条高度
let bottomBarH: CGFloat = 49

private enum TouchMoveDerection {
   case Right, Down, Left
    /// 可失败枚举构造器, 参数可为"R"、"D"、"L"
    init?(symbol: Character) {
        
        switch symbol {
        case "R":
            self = .Right
        case "D":
            self = .Down
        case "L":
            self = .Left
        default:
            return nil
        }
    }
}

class HomeViewController: UIViewController {
    
    override func prefersStatusBarHidden() -> Bool {
        return true
    }
    
    // 主题列表视图模型
    lazy var listViewModel = TopicListViewModel()
    
    /// 最新主题是否推送
    var lastTopicDidPublish:Bool = true
    
    /// 是否响应拖拽
    var canResponseToTouch:Bool = true
    
//MARK: - 懒加载UI控件
    /// 主题视图
   lazy var contentView: UITableView = UITableView()
    
    /// 背景
    lazy var bgView = UIImageView(image: UIImage(named: "sm_timeline_default_bg"))
    
    /// 下一主题更新时间提示视图
    lazy var promptTimeView: UIView = {
       
        let promptTimeView = UIView(frame: CGRectMake(0, 0, 150, 200))
   
        //second_hand
        let secondHand = UIImageView(image: UIImage(named: "sm_second_hand"))
        promptTimeView.addSubview(secondHand)
        secondHand.snp_makeConstraints(closure: { (make) -> Void in
            make.center.equalTo(promptTimeView).offset(CGPointMake(0, -10))
        })
        //minute_hand
        let minuteHand = UIImageView(image: UIImage(named: "sm_minute_hand"))
        promptTimeView.addSubview(minuteHand)
        minuteHand.snp_makeConstraints(closure: { (make) -> Void in
            make.center.equalTo(promptTimeView).offset(CGPointMake(0, -10))
        })
        //hour_hand
        let hourHand = UIImageView(image: UIImage(named: "sm_hour_hand"))
        promptTimeView.addSubview(hourHand)
        hourHand.snp_makeConstraints(closure: { (make) -> Void in
            make.center.equalTo(promptTimeView).offset(CGPointMake(0, -10))
        })
        // next
        let next = UIImageView(image: UIImage(named: "sm_next"))
        promptTimeView.addSubview(next)
        next.snp_makeConstraints(closure: { (make) -> Void in
            make.center.equalTo(promptTimeView).offset(CGPointMake(0, -10))
        })
        
        // timeLabel
        let timeLabel = UILabel()
        timeLabel.text = "07:58:33"
        timeLabel.textColor = UIColor.lightGrayColor()
        
        promptTimeView.addSubview(timeLabel)
        timeLabel.snp_makeConstraints(closure: { (make) -> Void in
            make.centerX.equalTo(promptTimeView)
            make.top.equalTo(secondHand.snp_bottom).offset(8)
        })
        
        return promptTimeView
    }()
    
    /// 用户头像
    lazy var userAccountIcon = UIButton(type: .Custom)
    
    /// 底部工具条
    lazy var bottomBar: UIView = {
        let bottomBar = UIView()
        bottomBar.backgroundColor = UIColor.blackColor()

        return bottomBar
    }()
    
    /// 毛玻璃
    lazy var blurView: UIVisualEffectView = {
        let effect = UIBlurEffect(style: UIBlurEffectStyle.Dark)
        let blurView = UIVisualEffectView(effect: effect)
        blurView.frame = ScreenBounds
        blurView.alpha = 1
        //blurView.backgroundColor = UIColor(white: 0.3, alpha: 1)
        var tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "recover")
        blurView.addGestureRecognizer(tap)
        
        return blurView
    }()
    
//    /// 蒙版
//    lazy var blurView: UIView = {
//        
//        let blurView = UIView(frame: ScreenBounds)
//        blurView.backgroundColor = UIColor(white: 0.4, alpha: 0.6)
//        
//        var tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "recover")
//        blurView.addGestureRecognizer(tap)
//        return blurView
//    }()

    
    /// 分类菜单
    lazy var sliderMenu: UIView = {
        let sliderMenu = SliderMenuView(frame: CGRectMake(0, 0, 290, 290))
        sliderMenu.center = self.view.center
        
        return sliderMenu
    }()
    
    
//MARK: - 生命周期
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.blackColor()

        contentView.backgroundColor = UIColor.clearColor()
        
        layoutUI()
        
        // 设置用户头像
        setupUserAccountIcon()
        
        // 设置底部工具条
        setupBottomBar()
    
        
        // 设置主题内容
        setupTopicContent()
        
       // lastTopicDidPublish ? print("---") :  view.addSubview(promptTimeView)
        
        // 手势
        setupGestrue()

    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        //设置透明NavBar
        self.navigationController?.navigationBar.lt_setBackgroundColor(UIColor.clearColor())
        self.navigationController?.navigationBar.shadowImage = UIImage()
    }
    
    /// 设置用户头像
    private func setupUserAccountIcon() {
        userAccountIcon.setBackgroundImage(UIImage(named: "chat_default_user_icon"), forState: .Normal)
    }
    
    /// 设置主题内容
    private func setupTopicContent() {
        
        contentView.separatorStyle = UITableViewCellSeparatorStyle.None
        contentView.bounces = false
        contentView.showsVerticalScrollIndicator = false
        
        contentView.registerNib(UINib(nibName: "TopicCell", bundle: nil), forCellReuseIdentifier: TopicCellRID)
        
        loadTopicData()
        
    }
    // MARK: 数据加载
    func loadTopicData() {
        
        listViewModel.loadLastestTopic{ (error) -> () in
            
            if error != nil {
                SVProgressHUD.showInfoWithStatus("您的网路不给力")
                return
            }
            // FIXME: 数据加载完之后再响应数据源方法，否则会报 数组越界 的错误
            self.contentView.delegate = self
            self.contentView.dataSource = self
            
            self.contentView.reloadData()
        }
    }
    
    /// 设置底部工具条
    private func setupBottomBar() {
        /// 添加功能按钮
        func addButton(imageName: String, index: Int) {
            let btn: UIButton = UIButton(type: UIButtonType.Custom)
            btn.setImage(UIImage(named: imageName), forState: UIControlState.Normal)
            btn.imageView?.contentMode = UIViewContentMode.ScaleAspectFit
            let width = bottomBar.width
            btn.frame = CGRectMake(CGFloat(index) * width * 0.5, 0, width * 0.5, bottomBar.height)
            btn.tag = index
            // 点击事件
            btn.addTarget(self, action: "barButtonDidClick:", forControlEvents: UIControlEvents.TouchUpInside)
            
            bottomBar.addSubview(btn)
        }
        // top分隔线
        let topLine = UIView(frame: CGRectMake(0, 0, bottomBar.width, 1))
        topLine.backgroundColor = UIColor.whiteColor()
        topLine.alpha = 0.4
        bottomBar.addSubview(topLine)
        
        // 中间分隔线
        let middleLine = UIImageView(image: UIImage(named: "ToolbarBG"))
        middleLine.center = CGPointMake(bottomBar.width * 0.5, bottomBarH * 0.5)
        bottomBar.addSubview(middleLine)
        
        
        addButton("sm_collect", index: 0)
        addButton("sm_history", index: 1)
    }
    
    func barButtonDidClick(btn: UIButton) {
        hiddenBottomBar()
        
        if btn.tag == 0 {
            
        } else {
        
            self.navigationController?.pushViewController(HistoryViewController(), animated: true)
        }
    }
    
//MARK: 布局视图
    private func layoutUI() {
    
       // view.insertSubview(bgView, atIndex: 0)
        view.addSubview(bgView)
        
        bgView.addSubview(promptTimeView)
        
//       view.insertSubview(bottomBar, belowSubview: self.bgView)
        
        
        view.addSubview(contentView)
        
        view.addSubview(bottomBar)
        
      //  view.addSubview(userAccountIcon)
        
        //自动布局
        bgView.snp_makeConstraints(closure: { (make) -> Void in
            make.top.left.right.bottom.equalTo(self.view)
        })
        
        promptTimeView.snp_makeConstraints(closure: { (make) -> Void in
            make.center.equalTo(bgView).offset(CGPointMake(0, 90))
        })
    
        bottomBar.snp_makeConstraints { (make) -> Void in
            make.height.equalTo(bottomBarH)
            make.left.right.equalTo(view)
            make.bottom.equalTo(view)//.offset(-bottomBarH)
//            make.width.equalTo(ScreenWidth)
//            make.baseline.equalTo(20)
        }
        bottomBar.layoutIfNeeded() // 如果不刷新按钮的frame极小
        
        contentView.snp_makeConstraints { (make) -> Void in
            make.top.leading.right.equalTo(view)
            make.bottom.equalTo(view).offset(-bottomBarH)
        }
        
        userAccountIcon.snp_makeConstraints { (make) -> Void in
            make.width.height.equalTo(41)
            make.centerX.equalTo(view)
            make.bottom.equalTo(view).offset(-20)
        }
        
        
    }
    
    //MARK: 手势添加
    override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {

        if !canResponseToTouch {
            return
        }
        
        let touch = (touches as NSSet).anyObject() as! UITouch
        
        // 当前点
        let currentP = touch.locationInView(view)
        // 上一个点
        let previousP = touch.previousLocationInView(view)
//        //获取偏移量
//        let offsetX: CGFloat = currentP.x - previousP.x
//        let offsetY: CGFloat = currentP.y - previousP.y
        let angle: CGFloat = MathTool.angleBetweenPoints(previousP, endP: currentP)
        
        var derection = TouchMoveDerection(symbol: "h")
        switch angle {
        case 225..<315: //向上滑动
            showBottomBar()
        case 315..<360, 0..<45: //向右滑动
            derection = TouchMoveDerection(symbol: "R")
            showSliderMenuView(derection!)
        case 45..<135: //向下滑动
            derection = TouchMoveDerection(symbol: "D")
            showSliderMenuView(derection!)
        default:  //向左滑动
            derection = TouchMoveDerection.Left
            showSliderMenuView(derection!)
        }
    }
    
    private func setupGestrue() {
        
        // 向上轻扫
//        let upSwipeGes = UISwipeGestureRecognizer(target: self, action: "showBottomBar")
//        upSwipeGes.direction = .Up
//        
//        view.addGestureRecognizer(upSwipeGes)
        
        // 其他方向
//        let downSwipeGes = UISwipeGestureRecognizer(target: self, action: "showSliderMenuView")
//        downSwipeGes.direction = .Down
//        view.addGestureRecognizer(downSwipeGes)
    }

    /// 展示主题菜单
   private func showSliderMenuView(derection: TouchMoveDerection) {
        
        canResponseToTouch = false
        // 蒙板
        view.addSubview(blurView)
    
        // 圆点
        let playCircle = UIImageView(image: UIImage(named: "sm_play_circle"))
        blurView.addSubview(playCircle)
    
        switch derection {
        case .Right:
            playCircle.center = CGPointMake(ScreenWidth * 0.25, ScreenHeight * 0.5)
        case .Down:
            playCircle.center = CGPointMake(ScreenWidth * 0.5, ScreenHeight * 0.25)
        case .Left:
            playCircle.center = CGPointMake(ScreenWidth * 0.75, ScreenHeight * 0.5)
        }
    
        UIView.animateWithDuration(1.5, delay: 0.1, usingSpringWithDamping: 0.8, initialSpringVelocity: 10, options: UIViewAnimationOptions.CurveEaseIn, animations: { () -> Void in
            
            playCircle.center = CGPointMake(ScreenWidth * 0.5, ScreenHeight * 0.5)
            
            }) { (_) -> Void in
                
              playCircle.removeFromSuperview()
              self.blurView.addSubview(self.sliderMenu)
        }
    
    }
    
    /**
     *  {
     CGFloat m11（x缩放）, m12（y切变）, m13（）, m14（）;
     CGFloat m21（x切变）, m22（y缩放）, m23（）, m24（）;
     CGFloat m31（）, m32（）, m33（）, m34（透视效果，要操作的这个对象要有旋转的角度，否则没有效果。当然,z方向上得有变化才会有透视效果）;
     CGFloat m41（x平移）, m42（y平移）, m43（z平移）, m44（）;
     };
     ps:
     
     整体比例变换时，也就是m11==m22时，若m33>1，图形整体缩小，若0<m33<1，图形整体放大，若m33<0,发生关于原点的对称等比变换。
     单设ｍ12或ｍ21的时候是切变效果，当【ｍ12=角度】和【ｍ21=－角度】的时候就是旋转效果了。两个角度值相同。
     */
    /// 显示底部工具条
    func showBottomBar() {
        
        canResponseToTouch = false
        
        let angle: CGFloat = CGFloat(-65 / 360.0 * M_PI)
//        let trans3D: CATransform3D = CATransform3DMakeRotation(angle, 1, 0, 0)
        var trans3D = CATransform3DIdentity
        trans3D.m34 = -1.0 / 1000.0
        trans3D = CATransform3DRotate(trans3D, angle, 1, 0, 0)
        
        UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.9, initialSpringVelocity: 5, options: UIViewAnimationOptions.CurveEaseInOut, animations: {    self.bgView.layer.transform = trans3D
            
            self.bottomBar.transform = CGAffineTransformMakeTranslation(0, -bottomBarH)
            
             self.userAccountIcon.alpha = 0
            }, completion: {(finished: Bool) in
        })
        
        let cover = UIView(frame: CGRectMake(0, 0, ScreenWidth, ScreenHeight - bottomBarH))
        cover.alpha = 0.3
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "hiddenBottomBar")
        cover.addGestureRecognizer(tap)
        view.addSubview(cover)
    }
    
    func hiddenBottomBar() {

        UIView.animateWithDuration(0.7, animations: { () -> Void in
            // 复原
            self.bgView.layer.transform = CATransform3DIdentity
            self.bottomBar.transform = CGAffineTransformIdentity
            
            }) { (_) -> Void in
                UIView.animateWithDuration(0.5, animations: { () -> Void in
                     self.userAccountIcon.alpha = 1
                })
        }
        
        canResponseToTouch = true
    }
    
    func recover() {
        blurView.removeFromSuperview()
        
        canResponseToTouch = true
    }
}

// MARK: - 数据源与代理
extension HomeViewController: UITableViewDataSource, UITableViewDelegate, UIGestureRecognizerDelegate {
 
     func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return lastTopicDidPublish ? 2 : 1//listViewModel.topics.count
    }
    
     func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        var vm: TopicViewModel = listViewModel.topics[indexPath.row]
        
        if lastTopicDidPublish {
            // 1. 取出视图模型
            switch indexPath.row {
            case 0:
                 vm = listViewModel.topics[indexPath.row + 1]
            case 1:
                 vm = listViewModel.topics[indexPath.row - 1]
            default:
                break
            }
        }
        
        // 2. 获取可重用 cell
        let cell = tableView.dequeueReusableCellWithIdentifier(TopicCellRID, forIndexPath: indexPath) as! TopicCell
        
        // 3. 设置视图模型
        cell.viewModel = vm
        cell.timeView.height = 0
        return cell
    }
    
     func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
        return ScreenHeight * 0.5 - bottomBarH / 2 //listViewModel.topics[indexPath.row].rowHeight
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
        var vm = listViewModel.topics[indexPath.row]
        
        if lastTopicDidPublish {
            // 1. 取出视图模型
            switch indexPath.row {
            case 0:
                vm = listViewModel.topics[indexPath.row + 1]
            case 1:
                vm = listViewModel.topics[indexPath.row - 1]
            default:
                break
            }
        }
        
        self.navigationController?.pushViewController(DetailViewController(topicVM: vm), animated: true)
    }
    
}

